#include "ledmodule.h"

#include <stdio.h>

unsigned long state;

int main(int argc, char **argv){
  initled();
  return 0;
}

PyMODINIT_FUNC initled(void){
  PyObject *module_methods, *module_dictionary;
  
  module_methods = Py_InitModule("led",ledmethods);
  module_dictionary = PyModule_GetDict(module_methods);
  return;
}

static PyObject *led_on(PyObject *self, PyObject *args){
  char *dev_path;
  int value;
  int fd;
  
  PyArg_ParseTuple(args,"si",&dev_path,&value);
  fd=open(dev_path, O_NOCTTY);

  ioctl(fd, KDGETLED, &state);
  usleep(50000);
  state|=value;
  ioctl(fd, KDSETLED, state);
  usleep(50000);
  
  close(fd);
  
  return Py_BuildValue("i",0);
}

static PyObject *led_off(PyObject *self, PyObject *args){
  char *dev_path;
  int value;
  int fd;
  
  PyArg_ParseTuple(args,"si",&dev_path,&value);
  fd=open(dev_path, O_NOCTTY);

  ioctl(fd, KDGETLED, &state);
  usleep(50000);
  state&=~value;
  ioctl(fd, KDSETLED, state);
  usleep(50000);
  
  close(fd);
  
  return Py_BuildValue("i",0);
}

static PyObject *led_set(PyObject *self, PyObject *args){
  char *dev_path;
  int value;
  int fd;
  
  PyArg_ParseTuple(args,"si",&dev_path,&value);
  fd=open(dev_path, O_NOCTTY);

  ioctl(fd, KDGETLED, &state);
  usleep(50000);
  state&=~7;
  state|=value;
  ioctl(fd, KDSETLED, state);
  usleep(50000);
  
  close(fd);
  
  return Py_BuildValue("i",0);
}

static PyObject *led_toggle(PyObject *self, PyObject *args){
  char *dev_path;
  int value;
  int fd;
  
  PyArg_ParseTuple(args,"si",&dev_path,&value);
  fd=open(dev_path, O_NOCTTY);

  ioctl(fd, KDGETLED, &state);
  usleep(50000);
  state^=value;
  ioctl(fd, KDSETLED, state);
  usleep(50000);
  
  close(fd);
  
  return Py_BuildValue("i",0);
}
